package com.zeny.coding.util;


import com.zeny.coding.constants.CourseConstants;
import org.springframework.util.StringUtils;

import javax.xml.bind.ValidationException;

/**
 * <h2>Dto校验工具</h2>
 *
 * @Author Zeny
 */
@SuppressWarnings("all")
public class DtoUtil {

    public static void require(String value) throws ValidationException {
        if (StringUtils.isEmpty(value)) {
            throw new ValidationException(CourseConstants.REQUEST_PARAMS_ERROR);
        }
    }
    public static void require(Integer value) throws ValidationException {
        if (value == null || value <= 0) {
            throw new ValidationException(CourseConstants.REQUEST_PARAMS_ERROR);
        }
    }

    private static void validLength(String value, Integer min, Integer max) throws ValidationException {
        int length = value.length();
        if (length > max || length < min) {
            throw new ValidationException(CourseConstants.REQUEST_PARAMS_ERROR);
        }
    }
    /**
     * <h2>校验</h2>
     * @param value 内容
     * @param required 是否必要
     * @param min 最小长度
     * @param max 最大长度
     **/
    public static void valid(String value, Boolean required, Integer min, Integer max) throws ValidationException {
        //非必要的值 required: true 必要 false: 不必要
        if (!required) {
            //存在并且是不在指定范围则抛出校验异常
            if (!StringUtils.isEmpty(value)) {
                //检查长度
                validLength(value, min, max);
            }
            return;
        }
        //必要的值
        require(value);
        validLength(value, min, max);
    }
}
